/**
 * @FileName: RpcInvocationHandler.java
 * @Package: com.ziroom.sms.std.rpc
 * @author liusq23
 * @created 2017/3/10 上午9:46
 * <p>
 * Copyright 2015 ziroom
 */
package com.ziroom.sms.std.rpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author liusq23
 * @version 1.0
 * @since 1.0
 */
public class RpcInvocationHandler implements InvocationHandler, net.sf.cglib.proxy.InvocationHandler {


    private String host;
    private int port;


    public RpcInvocationHandler(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Socket socket = null;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(host, port));
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            out.writeUTF(method.getName());
            out.writeObject(method.getParameterTypes());
            out.writeObject(args);
            out.flush();
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
            Object obj = in.readObject();
            if (obj instanceof Throwable) {
                return obj;
            }
            return obj;
        } catch (Exception e) {
            throw e;
        } finally {
            if (socket == null) {
                socket.close();
            }
        }
    }
}
